// ==UserScript==
// @name         接口地址管理器 v2.9 - axios风格配置版
// @namespace    http://tampermonkey.net/
// @version      2.9
// @description  提取页面接口地址，支持文字按钮和新格式生成，可配置axios风格
// @author       You
// @match        http://192.168.99.206:3000/*/*
// @grant        GM_setClipboard
// ==/UserScript==

(function () {
  "use strict";

  // 检查页面是否已加载完成
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", init);
  } else {
    init();
  }

  function init() {
    if (document.getElementById("api-manager-panel")) {
      return;
    }

    const panel = createPanel();
    document.body.appendChild(panel);
    renderInterfaces();
  }

  function createPanel() {
    const panel = document.createElement("div");
    panel.id = "api-manager-panel";
    panel.classList.add("minimized");
    panel.innerHTML = `
            <div class="api-panel-header">
                <h3>接口生成</h3>
                <div class="header-actions">
                    <div class="config-section"> 
                        <label class="config-label"  style="margin-right:10px">
                            <input type="checkbox" id="mock-prefix-toggle" ${
                              loadMockPrefix() ? "checked" : ""
                            }>
                            <span>mock前缀</span>
                        </label>
                        <label class="config-label">
                            <input type="checkbox" id="axios-style-toggle" ${
                              loadAxiosStyle() ? "checked" : ""
                            }>
                            <span>axios风格</span>
                        </label>
                    </div>
                    <button class="api-btn api-btn-primary" id="extract-current-btn">提取接口</button>
                    <button class="api-btn api-btn-info" id="batch-extract-btn">批量提取</button>
                    <button class="api-btn api-btn-success" id="copy-all-btn">复制全部</button>
                    <button class="api-btn api-btn-danger" id="clear-all-btn">清空</button>
                    <button class="minimize-btn" id="minimize-btn">−</button>
                </div>
            </div>
            <div class="api-panel-body" id="api-panel-body">
                <h3 id="total-count">共计:0</h3>
                <div class="interface-list" id="interface-list">
                    <div class="empty-state">暂无接口数据</div>
                </div>
            </div>
        `;

    // 添加样式
    const style = document.createElement("style");
    style.textContent = `
            #api-manager-panel {
                position: fixed;
                top: 20px;
                right: 20px;
                width: 650px; /* 增加面板宽度 */
                max-height: 600px;
                background: white;
                border-radius: 8px;
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
                z-index: 10000;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                font-size: 13px;
                transition: all 0.3s ease;
            }

            #api-manager-panel.minimized {
                height: 50px;
                overflow: hidden;
            }

            #api-manager-panel .api-panel-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 12px 16px;
                background: #f5f5f5;
                border-bottom: 1px solid #e8e8e8;
                border-radius: 8px 8px 0 0;
            }

            #api-manager-panel .api-panel-header h3 {
                margin: 0;
                font-size: 14px;
                font-weight: 600;
                color: #262626;
            }

            #api-manager-panel .header-actions {
                display: flex;
                gap: 8px;
                align-items: center;
            }

            #api-manager-panel .config-section {
                display: flex;
                align-items: center;
                margin-right: 8px;
            }

            #api-manager-panel .config-label {
                display: flex;
                align-items: center;
                font-size: 12px;
                color: #666;
                cursor: pointer;
                white-space: nowrap;
                user-select: none;
            }

            #api-manager-panel .config-label input[type="checkbox"] {
                margin-right: 4px;
                user-select: none;
                cursor: pointer;
            }

            #api-manager-panel .config-label span {
                cursor: pointer;
                 user-select: none;
            }

            #api-manager-panel .api-btn,#batch-extract-modal .api-btn {
                padding: 6px 12px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                background: white;
                font-size: 12px;
                cursor: pointer;
                transition: all 0.3s;
                white-space: nowrap;
            }

            #api-manager-panel .api-btn-primary,#batch-extract-modal .api-btn-primary {
            border-color: #1890ff;
            background: #1890ff;
            color: white;
            }

            #api-manager-panel .api-btn-primary:hover,#batch-extract-modal .api-btn-primary:hover {
            background: #69b1ff;
            border-color: #69b1ff;
            color: white;
            }

            #api-manager-panel .api-btn-success,#batch-extract-modal .api-btn-success {
            border-color: #52c41a;
            background: #52c41a;
            color: white;
            }

            #api-manager-panel .api-btn-success:hover,#batch-extract-modal .api-btn-success:hover {
            background: #95de64;
            border-color: #95de64;
            color: white;
            }

            #api-manager-panel .api-btn-danger,#batch-extract-modal .api-btn-danger {
            border-color: #ff4d4f;
            background: #ff4d4f;
            color: white;
            }

            #api-manager-panel .api-btn-danger:hover,#batch-extract-modal .api-btn-danger:hover {
            background: #ff8598;
            border-color: #ff8598;
            color: white;
            }

            #api-manager-panel .api-btn-info,#batch-extract-modal .api-btn-info {
            border-color: #13c2c2;
            background: #13c2c2;
            color: white;
            }

            #api-manager-panel .api-btn-info:hover,#batch-extract-modal .api-btn-info:hover {
            background: #63e6e6;
            border-color: #63e6e6;
            color: white;
            }

            #api-manager-panel .minimize-btn,#batch-extract-modal .minimize-btn {
                width: 24px;
                height: 24px;
                border: none;
                background: none;
                font-size: 16px;
                cursor: pointer;
                color: #666;
            }

            #api-manager-panel .minimize-btn:hover,#batch-extract-modal .minimize-btn:hover {
                background: #e6e6e6;
                border-radius: 4px;
            }

            #api-manager-panel .api-panel-body {
                padding: 0;

            }

            #api-manager-panel .interface-list {
                padding: 0;
                min-height:120px;
                max-height: 350px;
                overflow-y: auto;
            }

            #api-manager-panel .interface-item {
                display: flex;
                align-items: stretch;
                border-bottom: 1px solid #f0f0f0;
                transition: background-color 0.2s;
            }

            #api-manager-panel .interface-item:hover {
                background-color: #fafafa;
            }

            #api-manager-panel .interface-drag-handle {
                width: 30px;
                display: flex;
                align-items: center;
                justify-content: center;
                cursor: move;
                background-color: #f8f8f8;
                border-right: 1px solid #f0f0f0;
            }

            #api-manager-panel .interface-drag-handle:hover {
                background-color: #f0f0f0;
            }

            #api-manager-panel .interface-drag-handle::before {
                content: "⋮⋮";
                color: #ccc;
                font-size: 16px;
                line-height: 1;
            }

            #api-manager-panel .interface-name {
                width: 160px;
                padding: 12px 8px;
                border-right: 1px solid #f0f0f0;
                font-size: 12px;
                color: #666;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                display: flex;
                align-items: center;
            }

            #api-manager-panel .interface-content {
                flex: 1;
                padding: 12px 16px;
                border-right: 1px solid #f0f0f0;
                min-width: 0;
            }

            #api-manager-panel .interface-code {
                font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
                font-size: 12px;
                line-height: 1.4;
                color: #262626;
                word-break: break-all;
                white-space: pre-wrap;
            }

            #api-manager-panel .interface-actions {
                display: flex;
                align-items: center;
                padding: 8px 12px;
                gap: 8px;
                min-width: 100px;
            }

            #api-manager-panel .interface-btn {
                padding: 4px 8px;
                border: 1px solid #d9d9d9;
                border-radius: 3px;
                background: white;
                font-size: 11px;
                cursor: pointer;
                transition: all 0.2s;
                text-align: center;
                height: 24px;
                line-height: 16px;
            }

            #api-manager-panel .interface-btn:hover {
                border-color: #40a9ff;
                color: #40a9ff;
            }

            #api-manager-panel .interface-btn.copy-btn {
                border-color: #52c41a;
                color: #52c41a;
            }

            #api-manager-panel .interface-btn.copy-btn:hover {
                background: #52c41a;
                color: white;
            }

            #api-manager-panel .interface-btn.delete-btn {
                border-color: #ff4d4f;
                color: #ff4d4f;
            }

            #api-manager-panel .interface-btn.delete-btn:hover {
                background: #ff4d4f;
                color: white;
            }

            #api-manager-panel .empty-state {
                padding: 40px 20px;
                text-align: center;
                color: #999;
                font-size: 13px;
            }

            .toast {
                position: fixed;
                top: 40px;
                right: 620px;
                padding: 8px 16px;
                border-radius: 4px;
                color: white;
                font-size: 13px;
                z-index: 10001;
                opacity: 0;
                transition: opacity 0.3s;
            }

            .toast.success {
                background: #52c41a;
            }

            .toast.error {
                background: #ff4d4f;
            }

            .toast.show {
                opacity: 1;
            }

            /* 批量提取弹窗样式 */
            #batch-extract-modal {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                display: none;
                justify-content: center;
                align-items: center;
                z-index: 10002;
            }

            #batch-extract-modal .modal-content {
                background: white;
                border-radius: 8px;
                width: 600px;
                max-height: 70vh;
                display: flex;
                flex-direction: column;
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            }

            #batch-extract-modal .modal-header {
                padding: 16px 20px;
                border-bottom: 1px solid #e8e8e8;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }

            #batch-extract-modal .modal-header h3 {
                margin: 0;
                font-size: 16px;
                font-weight: 600;
                color: #262626;
            }

            #batch-extract-modal .modal-close {
                background: none;
                border: none;
                font-size: 18px;
                cursor: pointer;
                color: #666;
                width: 24px;
                height: 24px;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            #batch-extract-modal .modal-close:hover {
                color: #262626;
            }

            #batch-extract-modal .modal-body {
                padding: 20px;
                overflow-y: auto;
                flex: 1;
            }

            #batch-extract-modal .modal-footer {
                padding: 16px 20px;
                border-top: 1px solid #e8e8e8;
                display: flex;
                justify-content: flex-end;
                gap: 12px;
            }

            #batch-extract-modal .picked-items {
                margin-top: 16px;
            }

            #batch-extract-modal .picked-item {
                padding: 8px 12px;
                background: #f5f5f5;
                border-radius: 4px;
                margin-bottom: 8px;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }

            #batch-extract-modal .picked-item-name {
                font-size: 13px;
                color: #262626;
            }

            #batch-extract-modal .remove-item-btn {
                background: #ff4d4f;
                color: white;
                border: none;
                border-radius: 3px;
                padding: 4px 8px;
                font-size: 11px;
                cursor: pointer;
            }

            #batch-extract-modal .remove-item-btn:hover {
                background: #ff7875;
            }

            #batch-extract-modal .start-pick-btn {
                padding: 8px 16px;
                background: #1890ff;
                color: white;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 13px;
            }

            #batch-extract-modal .start-pick-btn:hover {
                background: #40a9ff;
            }

            .generating-overlay {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(255, 255, 255, 0.9);
                display: none;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                z-index: 10003;
            }

            .generating-content {
                text-align: center;
                padding: 24px;
            }

            .generating-spinner {
                width: 40px;
                height: 40px;
                border: 3px solid #f3f3f3;
                border-top: 3px solid #1890ff;
                border-radius: 50%;
                animation: spin 1s linear infinite;
                margin: 0 auto 16px;
            }

            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }

            .generating-text {
                font-size: 14px;
                color: #262626;
            }
        `;
    document.head.appendChild(style);

    bindEvents(panel);
    return panel;
  }

  // 修改bindEvents函数中的axios风格切换事件处理
  function bindEvents(panel) {
    panel.querySelector("#minimize-btn").addEventListener("click", function () {
      panel.classList.toggle("minimized");
      this.textContent = panel.classList.contains("minimized") ? "+" : "−";
    });

    panel
      .querySelector("#axios-style-toggle")
      .addEventListener("change", function () {
        saveAxiosStyle(this.checked);
        // 重新生成并显示所有接口
        regenerateAllInterfaces(this.checked);
        showToast(
          this.checked ? "已切换到axios风格" : "已切换到简洁风格",
          "success"
        );
      });

    // 添加mock前缀切换事件
    panel
      .querySelector("#mock-prefix-toggle")
      .addEventListener("change", function () {
        saveMockPrefix(this.checked);
        // 重新生成并显示所有接口
        regenerateAllInterfacesByMockPrefix(this.checked);
        showToast(
          this.checked ? "已启用mock前缀" : "已禁用mock前缀",
          "success"
        );
      });

    panel
      .querySelector("#extract-current-btn")
      .addEventListener("click", function () {
        extractCurrentInterface();
      });

    panel.querySelector("#copy-all-btn").addEventListener("click", function () {
      copyAllInterfaces();
    });

    panel
      .querySelector("#clear-all-btn")
      .addEventListener("click", function () {
        clearAllInterfaces();
      });

    panel
      .querySelector("#batch-extract-btn")
      .addEventListener("click", function () {
        showBatchExtractModal();
      });
  }

  function generateFunctionName(method, url) {
    // 获取URL最后一个有效单词
    const parts = url.split("/");
    let lastWord = "api";

    for (let i = parts.length - 1; i >= 0; i--) {
      const part = parts[i]
        .replace(/\$\{[^}]+\}/g, "")
        .replace(/[^a-zA-Z0-9]/g, "");
      if (part && part.length > 0) {
        lastWord = part.toLowerCase();
        break;
      }
    }

    // 根据请求方法确定前缀
    let prefix = "get";
    switch (method.toLowerCase()) {
      case "get":
        prefix = "get";
        break;
      case "post":
        prefix = "add";
        break;
      case "put":
        prefix = "put";
        break;
      case "delete":
        prefix = "del";
        break;
      default:
        prefix = method.toLowerCase();
    }

    return `${prefix}${lastWord.charAt(0).toUpperCase()}${lastWord.slice(1)}`;
  }

  function generateParams(url, method) {
    const params = [];

    // 检查路径参数
    const pathParams = url.match(/\$\{([^}]+)\}/g);
    if (pathParams && pathParams.length > 0) {
      if (pathParams.length === 1) {
        // 只有一个路径参数时，直接使用该参数名
        const paramName = pathParams[0].replace(/\$\{([^}]+)\}/g, "$1");
        params.push(paramName);
      } else {
        // 多个路径参数时，使用pathParams对象
        params.push("pathParams");
      }
    }

    // 检查Query参数（GET请求）
    if (method === "GET") {
      const hasRequestParams = hasTextInPage("请求参数");
      const hasQuery = hasTextInPage("Query");
      if (hasRequestParams && hasQuery) {
        params.push("params");
      }
    }

    // 检查请求体参数（POST/PUT请求）
    if (method === "POST" || method === "PUT") {
      params.push("data");
    }

    return params.join(", ") || "";
  }

  function replacePathParams(url, hasMultiplePathParams) {
    if (hasMultiplePathParams) {
      // 多个路径参数时，使用pathParams对象
      return url.replace(/\{([^}]+)\}/g, "${pathParams.$1}");
    } else {
      // 单个路径参数或没有路径参数时，直接使用参数名
      return url.replace(/\{([^}]+)\}/g, "${$1}");
    }
  }

  function hasTextInPage(text) {
    const bodyText = document.body.textContent || document.body.innerText || "";
    return bodyText.toLowerCase().includes(text.toLowerCase());
  }

  function renderInterfaces() {
    const interfaces = loadInterfaces();
    const panelBody = document.getElementById("api-panel-body");
    const totalCount = document.getElementById("total-count");
    const listContainer = document.getElementById("interface-list");

    console.log("renderInterfaces", interfaces, listContainer);

    if (interfaces.length === 0) {
      totalCount.innerText = "共计: 0";
      listContainer.innerHTML = '<div class="empty-state">暂无接口数据</div>';
      return;
    }

    totalCount.innerText = `共计：${interfaces.length}`;

    listContainer.innerHTML = "";

    interfaces.forEach((item, index) => {
      const interfaceItem = document.createElement("div");
      interfaceItem.className = "interface-item";
      interfaceItem.dataset.index = index;
      interfaceItem.innerHTML = `
                <div class="interface-drag-handle"></div>
                <div class="interface-name">${escapeHtml(
                  item.comment || "无名称"
                )}</div>
                <div class="interface-content">
                    <div class="interface-code">${escapeHtml(
                      item.displayCode
                    )}</div>
                </div>
                <div class="interface-actions">
                    <button class="interface-btn copy-btn" data-index="${index}">复制</button>
                    <button class="interface-btn delete-btn" data-index="${index}">删除</button>
                </div>
            `;
      listContainer.appendChild(interfaceItem);
    });

    // 初始化拖拽功能
    initDragAndDrop();

    listContainer.addEventListener("click", function (e) {
      if (e.target.classList.contains("copy-btn")) {
        const index = parseInt(e.target.dataset.index);
        copyInterface(index);
      } else if (e.target.classList.contains("delete-btn")) {
        const index = parseInt(e.target.dataset.index);
        deleteInterface(index);
      }
    });
  }

  // 初始化拖拽排序功能
  function initDragAndDrop() {
    const listContainer = document.getElementById("interface-list");
    const items = listContainer.querySelectorAll(".interface-item");
    let draggedItem = null;

    items.forEach((item) => {
      // 获取拖拽手柄
      const handle = item.querySelector(".interface-drag-handle");

      handle.addEventListener("dragstart", function () {
        draggedItem = item;
        setTimeout(() => {
          item.style.opacity = "0.5";
        }, 0);
      });

      handle.addEventListener("dragend", function () {
        draggedItem = null;
        items.forEach((item) => {
          item.style.opacity = "1";
          item.style.borderTop = "none";
        });
      });

      // 设置拖拽属性
      handle.setAttribute("draggable", "true");

      // 拖拽经过其他元素时的处理
      item.addEventListener("dragover", function (e) {
        e.preventDefault();
        return false;
      });

      item.addEventListener("dragenter", function (e) {
        e.preventDefault();
        if (this !== draggedItem) {
          const draggedIndex = parseInt(draggedItem.dataset.index);
          const currentIndex = parseInt(this.dataset.index);

          if (draggedIndex < currentIndex) {
            // 拖动到下方
            this.style.borderBottom = "2px solid #1890ff";
            this.style.borderTop = "none";
          } else {
            // 拖动到上方
            this.style.borderTop = "2px solid #1890ff";
            this.style.borderBottom = "none";
          }
        }
      });

      item.addEventListener("dragleave", function () {
        this.style.borderTop = "none";
        this.style.borderBottom = "none";
      });

      item.addEventListener("drop", function (e) {
        e.preventDefault();

        if (draggedItem !== this) {
          const interfaces = loadInterfaces();
          const draggedIndex = parseInt(draggedItem.dataset.index);
          const currentIndex = parseInt(this.dataset.index);

          // 从数组中移除拖动的元素
          const [removed] = interfaces.splice(draggedIndex, 1);
          // 在新位置插入元素
          interfaces.splice(currentIndex, 0, removed);

          // 保存新的排序
          saveInterfaces(interfaces);
          // 重新渲染列表
          renderInterfaces();

          showToast("接口排序已更新", "success");
        }

        this.style.borderTop = "none";
        this.style.borderBottom = "none";
      });
    });
  }

  function copyInterface(index) {
    const interfaces = loadInterfaces();
    const item = interfaces[index];

    if (copyToClipboard(item.finalCode)) {
      showToast("已复制完整代码到剪贴板", "success");
    }
  }

  function deleteInterface(index) {
    const interfaces = loadInterfaces();
    interfaces.splice(index, 1);
    saveInterfaces(interfaces);
    renderInterfaces();
    showToast("已删除", "success");
  }

  function copyAllInterfaces() {
    const interfaces = loadInterfaces();
    if (interfaces.length === 0) {
      showToast("暂无接口可复制", "error");
      return;
    }

    const allCode = interfaces.map((item) => item.finalCode).join("\n\n");
    if (copyToClipboard(allCode)) {
      showToast(`已复制全部 ${interfaces.length} 个接口`, "success");
    }
  }

  function clearAllInterfaces() {
    const interfaces = loadInterfaces();
    if (interfaces.length === 0) {
      showToast("暂无接口可清空", "error");
      return;
    }

    if (confirm("确定要清空所有接口吗？")) {
      saveInterfaces([]);
      renderInterfaces();
      showToast("已清空所有接口", "success");
    }
  }

  // 添加mock前缀相关函数
  function loadMockPrefix() {
    try {
      return localStorage.getItem("api-manager-mock-prefix") === "true";
    } catch {
      return false;
    }
  }

  function saveMockPrefix(useMockPrefix) {
    try {
      localStorage.setItem("api-manager-mock-prefix", useMockPrefix.toString());
    } catch (error) {
      console.error("保存mock前缀配置失败:", error);
    }
  }

  function loadInterfaces() {
    try {
      const saved = localStorage.getItem("api-manager-interfaces-v3");
      return saved ? JSON.parse(saved) : [];
    } catch {
      return [];
    }
  }

  function saveInterfaces(interfaces) {
    try {
      localStorage.setItem(
        "api-manager-interfaces-v3",
        JSON.stringify(interfaces)
      );
    } catch (error) {
      console.error("保存接口数据失败:", error);
    }
  }

  function loadAxiosStyle() {
    try {
      return localStorage.getItem("api-manager-axios-style") === "true";
    } catch {
      return false;
    }
  }

  function saveAxiosStyle(useAxiosStyle) {
    try {
      localStorage.setItem("api-manager-axios-style", useAxiosStyle.toString());
    } catch (error) {
      console.error("保存axios风格配置失败:", error);
    }
  }

  function copyToClipboard(text) {
    try {
      if (typeof GM_setClipboard !== "undefined") {
        GM_setClipboard(text);
        return true;
      }

      const textarea = document.createElement("textarea");
      textarea.value = text;
      textarea.style.position = "fixed";
      textarea.style.opacity = "0";
      document.body.appendChild(textarea);
      textarea.select();

      const success = document.execCommand("copy");
      document.body.removeChild(textarea);

      return success;
    } catch (error) {
      console.error("复制失败:", error);
      return false;
    }
  }

  function showToast(message, type = "success") {
    const toast = document.createElement("div");
    toast.className = `toast ${type}`;
    toast.textContent = message;
    document.body.appendChild(toast);

    setTimeout(() => toast.classList.add("show"), 10);
    setTimeout(() => {
      toast.classList.remove("show");
      setTimeout(() => document.body.removeChild(toast), 300);
    }, 2000);
  }

  function escapeHtml(text) {
    const div = document.createElement("div");
    div.textContent = text;
    return div.innerHTML;
  }

  // 修改addInterface函数，保存更多原始信息
  function addInterface(
    displayCode,
    finalCode,
    comment,
    funcName,
    url,
    method
  ) {
    const interfaces = loadInterfaces();

    const interfaceData = {
      displayCode: displayCode,
      finalCode: finalCode,
      comment: comment,
      funcName: funcName,
      // 保存原始信息以便后续重新生成代码
      originalUrl: url,
      method: method,
    };

    // 去重检查
    if (interfaces.some((item) => item.displayCode === displayCode)) {
      showToast("该接口已存在", "error");
      return;
    }

    interfaces.push(interfaceData);
    saveInterfaces(interfaces);
    renderInterfaces();
  }

  // 根据mock前缀配置重新生成所有接口
  function regenerateAllInterfacesByMockPrefix(useMockPrefix) {
    const interfaces = loadInterfaces();
    const updatedInterfaces = interfaces.map((item) => {
      // 如果是新版格式（有originalUrl），重新生成代码
      if (item.originalUrl && item.method) {
        // 重新处理URL参数
        const originalUrl = item.originalUrl;
        const pathParamMatches = originalUrl.match(/\{([^}]+)\}/g) || [];
        const hasMultiplePathParams = pathParamMatches.length > 1;
        let url = replacePathParams(originalUrl, hasMultiplePathParams);

        // 补全相对路径
        if (!url.startsWith("http")) {
          url =
            "http://192.168.99.206:3000" +
            (url.startsWith("/") ? "" : "/") +
            url;
        }

        // 处理mock前缀
        url = processMockPrefix(url, useMockPrefix);

        // 重新生成参数列表
        const params = generateParams(url, item.method);

        // 检查是否有路径参数
        const hasPathParams = url.includes("$");

        // 检查是否使用axios风格
        const useAxiosStyle = loadAxiosStyle();

        // 重新生成代码
        let displayCode, finalCode;
        if (useAxiosStyle) {
          // axios风格
          let config = `{ url: `;
          if (hasPathParams) {
            config += `\`${url}\``;
          } else {
            config += `'${url}'`;
          }

          if (item.method !== "GET") {
            config += `, method: '${item.method}'`;
          }

          if (item.method === "GET") {
            const hasRequestParams = hasTextInPage("请求参数");
            const hasQuery = hasTextInPage("Query");
            if (hasRequestParams && hasQuery) {
              config += `, params`;
            }
          } else if (item.method === "POST" || item.method === "PUT") {
            config += `, data`;
          }
          config += " }";

          displayCode = `axios.${item.method.toLowerCase()}(${config})`;
          finalCode = `/**\n * ${item.comment}\n */\nexport const ${item.funcName} = (${params}) => ${displayCode}`;
        } else {
          // 简洁风格
          let displayCodeSimple = `${item.method}(`;
          if (hasPathParams) {
            displayCodeSimple += `\`${url}\``;
          } else {
            displayCodeSimple += `'${url}'`;
          }

          if (item.method === "GET") {
            const hasRequestParams = hasTextInPage("请求参数");
            const hasQuery = hasTextInPage("Query");
            if (hasRequestParams && hasQuery) {
              displayCodeSimple += ", params";
            }
          } else if (item.method === "POST" || item.method === "PUT") {
            displayCodeSimple += ", data";
          }
          displayCodeSimple += ")";

          displayCode = displayCodeSimple;
          finalCode = `/**\n * ${item.comment}\n */\nexport const ${item.funcName} = (${params}) => ${displayCode}`;
        }

        return {
          ...item,
          displayCode: displayCode,
          finalCode: finalCode,
          url: url, // 保存处理后的URL
        };
      }
      // 旧版格式保持不变
      return item;
    });

    // 保存更新后的接口列表
    saveInterfaces(updatedInterfaces);
    // 重新渲染接口列表
    renderInterfaces();
  }

  // 处理mock前缀
  function processMockPrefix(url, useMockPrefix) {
    // 正则匹配mock地址部分 http://192.168.99.206:3000/mock/数字
    const mockPrefixRegex = /^http:\/\/192\.168\.99\.206:3000\/mock\/\d+\//;

    if (useMockPrefix) {
      // 如果需要添加mock前缀，但URL中还没有
      if (!mockPrefixRegex.test(url)) {
        // 提取基础URL（去掉可能的http://192.168.99.206:3000部分）
        let basePath = url.replace(/^http:\/\/192\.168\.99\.206:3000/, "");
        if (!basePath.startsWith("/")) {
          basePath = "/" + basePath;
        }
        // 检查URL中是否已经包含/mock/数字部分
        const existingMockMatch = basePath.match(/\/mock\/\d+/);
        if (existingMockMatch) {
          // 如果已经有mock部分，保留它
          return `http://192.168.99.206:3000${
            existingMockMatch[0]
          }${basePath.replace(existingMockMatch[0], "")}`;
        } else {
          // 如果没有mock部分，添加默认的/mock/804
          return `http://192.168.99.206:3000/mock/804${basePath}`;
        }
      }
    } else {
      // 如果需要移除mock前缀
      if (mockPrefixRegex.test(url)) {
        // 移除mock前缀部分
        return url.replace(mockPrefixRegex, "/");
      }
    }
    return url;
  }

  // 修改extractCurrentInterface函数，添加mock前缀处理
  function extractCurrentInterface() {
    try {
      // 查找接口地址
      const selectors = [
        ".colValue .href",
        ".colValue",
        "td:nth-child(2)",
        ".interface-url",
        "[data-url]",
        ".url-display",
      ];

      let url = null;
      for (const selector of selectors) {
        const element = document.querySelector(selector);
        if (element && element.textContent.trim()) {
          url = element.textContent.trim();
          break;
        }
      }

      if (!url) {
        const text = document.body.textContent;
        const urlMatch = text.match(/['"`]([^'"`\s]*\/mock\/[^'"`\s]*)['"`]/);
        if (urlMatch) {
          url = urlMatch[1];
        }
      }

      if (!url) {
        showToast("未找到接口地址", "error");
        return;
      }

      // 保存原始URL用于替换参数
      const originalUrl = url;
      // 保存原始URL（处理前的URL）
      const originalUrlBeforeProcessing = originalUrl;

      // 获取路径参数信息
      const pathParamMatches = url.match(/\{([^}]+)\}/g) || [];
      const hasSinglePathParam = pathParamMatches.length === 1;
      const hasMultiplePathParams = pathParamMatches.length > 1;

      // 替换路径参数 {id} -> ${id} 或 ${pathParams.id}
      url = replacePathParams(url, hasMultiplePathParams);

      // 补全相对路径
      if (!url.startsWith("http")) {
        url =
          "http://192.168.99.206:3000" + (url.startsWith("/") ? "" : "/") + url;
      }

      // 应用mock前缀配置
      const useMockPrefix = loadMockPrefix();
      url = processMockPrefix(url, useMockPrefix);

      // ... 后续代码保持不变 ...
      // 查找HTTP方法
      const methodSelectors = [".tag-method", ".http-method", ".method-tag"];
      let method = "GET";
      for (const selector of methodSelectors) {
        const element = document.querySelector(selector);
        if (element && element.textContent.trim()) {
          method = element.textContent.trim().toUpperCase();
          break;
        }
      }

      // 查找接口名称作为注释
      let comment = "接口调用";
      const commentSelectors = [
        '//*[text()="接口名称"]/following-sibling::*',
        ".interface-name",
        ".api-name",
        ".name-label",
        "td:nth-child(1)",
      ];

      // 尝试查找"接口名称"后面的元素
      const interfaceNameElements = document.evaluate(
        '//*[contains(text(), "接口名称")]/following-sibling::*[1]',
        document,
        null,
        XPathResult.FIRST_ORDERED_NODE_TYPE,
        null
      );

      if (interfaceNameElements.singleNodeValue) {
        comment = interfaceNameElements.singleNodeValue.textContent.trim();
      } else {
        // 回退方案
        for (const selector of commentSelectors.slice(1)) {
          const element = document.querySelector(selector);
          if (element && element.textContent.trim()) {
            comment = element.textContent.trim();
            break;
          }
        }
      }

      // 生成函数名
      const funcName = generateFunctionName(method, url);

      // 生成参数列表
      const params = generateParams(url, method);

      // 检查是否使用axios风格
      const useAxiosStyle = loadAxiosStyle();

      // 检查是否有路径参数
      const hasPathParams = url.includes("$");

      // 生成显示代码
      let displayCode, finalCode;

      if (useAxiosStyle) {
        // axios风格
        let config = `{ url: `;
        if (hasPathParams) {
          config += `\`${url}\``;
        } else {
          config += `'${url}'`;
        }

        if (method !== "GET") {
          config += `, method: '${method}'`;
        }

        if (method === "GET") {
          const hasRequestParams = hasTextInPage("请求参数");
          const hasQuery = hasTextInPage("Query");
          if (hasRequestParams && hasQuery) {
            config += `, params`;
          }
        } else if (method === "POST" || method === "PUT") {
          config += `, data`;
        }
        config += " }";

        displayCode = `axios.${method.toLowerCase()}(${config})`;
        finalCode = `/**\n * ${comment}\n */\nexport const ${funcName} = (${params}) => ${displayCode}`;
      } else {
        // 简洁风格
        let displayCodeSimple = `${method}(`;
        if (hasPathParams) {
          displayCodeSimple += `\`${url}\``;
        } else {
          displayCodeSimple += `'${url}'`;
        }

        if (method === "GET") {
          const hasRequestParams = hasTextInPage("请求参数");
          const hasQuery = hasTextInPage("Query");
          if (hasRequestParams && hasQuery) {
            displayCodeSimple += ", params";
          }
        } else if (method === "POST" || method === "PUT") {
          displayCodeSimple += ", data";
        }
        displayCodeSimple += ")";

        displayCode = displayCodeSimple;
        finalCode = `/**\n * ${comment}\n */\nexport const ${funcName} = (${params}) => ${displayCode}`;
      }

      // 添加到列表，传递更多原始信息
      addInterface(
        displayCode,
        finalCode,
        comment,
        funcName,
        originalUrlBeforeProcessing,
        method
      );
      showToast("接口提取成功", "success");
    } catch (error) {
      console.error("提取接口失败:", error);
      showToast("提取接口失败", "error");
    }
  }

  // 修改regenerateAllInterfaces函数，考虑mock前缀配置
  function regenerateAllInterfaces(useAxiosStyle) {
    const interfaces = loadInterfaces();
    const updatedInterfaces = interfaces.map((item) => {
      // 如果是新版格式（有originalUrl），重新生成代码
      if (item.originalUrl && item.method) {
        // 重新处理URL参数
        const originalUrl = item.originalUrl;
        const pathParamMatches = originalUrl.match(/\{([^}]+)\}/g) || [];
        const hasMultiplePathParams = pathParamMatches.length > 1;
        let url = replacePathParams(originalUrl, hasMultiplePathParams);

        // 补全相对路径
        if (!url.startsWith("http")) {
          url =
            "http://192.168.99.206:3000" +
            (url.startsWith("/") ? "" : "/") +
            url;
        }

        // 应用mock前缀配置
        const useMockPrefix = loadMockPrefix();
        url = processMockPrefix(url, useMockPrefix);

        // 重新生成参数列表
        const params = generateParams(url, item.method);

        // 检查是否有路径参数
        const hasPathParams = url.includes("$");

        // 重新生成代码
        let displayCode, finalCode;
        if (useAxiosStyle) {
          // axios风格
          let config = `{ url: `;
          if (hasPathParams) {
            config += `\`${url}\``;
          } else {
            config += `'${url}'`;
          }

          if (item.method !== "GET") {
            config += `, method: '${item.method}'`;
          }

          if (item.method === "GET") {
            const hasRequestParams = hasTextInPage("请求参数");
            const hasQuery = hasTextInPage("Query");
            if (hasRequestParams && hasQuery) {
              config += `, params`;
            }
          } else if (item.method === "POST" || item.method === "PUT") {
            config += `, data`;
          }
          config += " }";

          displayCode = `axios.${item.method.toLowerCase()}(${config})`;
          finalCode = `/**\n * ${item.comment}\n */\nexport const ${item.funcName} = (${params}) => ${displayCode}`;
        } else {
          // 简洁风格
          let displayCodeSimple = `${item.method}(`;
          if (hasPathParams) {
            displayCodeSimple += `\`${url}\``;
          } else {
            displayCodeSimple += `'${url}'`;
          }

          if (item.method === "GET") {
            const hasRequestParams = hasTextInPage("请求参数");
            const hasQuery = hasTextInPage("Query");
            if (hasRequestParams && hasQuery) {
              displayCodeSimple += ", params";
            }
          } else if (item.method === "POST" || item.method === "PUT") {
            displayCodeSimple += ", data";
          }
          displayCodeSimple += ")";

          displayCode = displayCodeSimple;
          finalCode = `/**\n * ${item.comment}\n */\nexport const ${item.funcName} = (${params}) => ${displayCode}`;
        }

        return {
          ...item,
          displayCode: displayCode,
          finalCode: finalCode,
          url: url, // 保存处理后的URL
        };
      }
      // 旧版格式保持不变
      return item;
    });

    // 保存更新后的接口列表
    saveInterfaces(updatedInterfaces);
    // 重新渲染接口列表
    renderInterfaces();
  }

  // 批量提取接口相关功能
  let pickedElements = [];
  let isPicking = false;
  let batchExtractUrls = [];
  let currentProcessingIndex = 0;

  // 显示批量提取弹窗
  function showBatchExtractModal() {
    // 检查是否已存在弹窗
    let modal = document.getElementById("batch-extract-modal");
    if (!modal) {
      modal = createBatchExtractModal();
      document.body.appendChild(modal);
    }

    modal.style.display = "flex";
    updatePickedItemsList();
  }

  // 创建批量提取弹窗
  function createBatchExtractModal() {
    const modal = document.createElement("div");
    modal.id = "batch-extract-modal";
    modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3>批量提取接口</h3>
                    <button class="modal-close" id="modal-close-btn">×</button>
                </div>
                <div class="modal-body">
                    <button class="start-pick-btn" id="start-pick-btn">开始拾取元素</button>
                    <div class="picked-items" id="picked-items-list"></div>
                </div>
                <div class="modal-footer">
                    <button class="api-btn" id="cancel-batch-btn">取消</button>
                    <button class="api-btn api-btn-success" id="generate-batch-btn">生成接口</button>
                </div>
            </div>
        `;

    // 绑定事件
    modal
      .querySelector("#modal-close-btn")
      .addEventListener("click", function () {
        modal.style.display = "none";
      });

    modal
      .querySelector("#cancel-batch-btn")
      .addEventListener("click", function () {
        modal.style.display = "none";
      });

    modal
      .querySelector("#start-pick-btn")
      .addEventListener("click", function () {
        startElementPicking();
      });

    modal
      .querySelector("#generate-batch-btn")
      .addEventListener("click", function () {
        if (pickedElements.length === 0) {
          showToast("请先拾取元素", "error");
          return;
        }
        startBatchGeneration();
      });

    return modal;
  }

  // 更新已拾取元素列表
  function updatePickedItemsList() {
    const listContainer = document.getElementById("picked-items-list");
    listContainer.innerHTML = "";

    if (pickedElements.length === 0) {
      listContainer.innerHTML =
        "<p style='color: #999; font-size: 12px;'>暂无拾取的元素</p>";
      return;
    }

    pickedElements.forEach((element, index) => {
      const a = element.current.querySelector("a.interface-item");
      const item = document.createElement("div");
      item.className = "picked-item";
      item.innerHTML = `
                <span class="picked-item-name">${a.innerText} (${element.children.length})</span>
                <button class="remove-item-btn" data-index="${index}">移除</button>
            `;
      listContainer.appendChild(item);

      // 绑定移除事件
      item
        .querySelector(".remove-item-btn")
        .addEventListener("click", function () {
          const _index = parseInt(this.dataset.index);
          pickedElements.splice(_index, 1);
          updatePickedItemsList();
        });
    });
  }

  // 开始元素拾取
  function startElementPicking() {
    // 隐藏弹窗
    const modal = document.getElementById("batch-extract-modal");
    modal.style.display = "none";

    // 设置拾取状态
    isPicking = true;

    // 创建半透明覆盖层
    const overlay = document.createElement("div");
    overlay.id = "picking-overlay";
    overlay.style.position = "fixed";
    overlay.style.top = "0";
    overlay.style.left = "0";
    overlay.style.width = "100%";
    overlay.style.height = "100%";
    overlay.style.background = "rgba(0, 0, 0, 0.3)";
    overlay.style.zIndex = "10001";
    overlay.style.cursor = "crosshair";
    overlay.style.display = "flex";
    overlay.style.flexDirection = "column";
    overlay.style.justifyContent = "center";
    overlay.style.alignItems = "center";
    overlay.style.color = "white";
    overlay.style.fontSize = "16px";
    overlay.style.userSelect = "none";
    overlay.innerHTML =
      "<p>点击要拾取的接口导航元素</p><p style='font-size: 14px; margin-top: 8px;' id='tips'>（按ESC键取消拾取),3秒后自动关闭</p>";
    document.body.appendChild(overlay);
    const tipsDom = overlay.querySelector("#tips");

    let count = 3;
    const timer = setInterval(() => {
      count--;
      tipsDom.innerText = `（按ESC键取消拾取),${count}秒后自动关闭`;
      if (count <= 0) {
        clearInterval(timer);
        if (overlay) {
          document.body.removeChild(overlay);
        }
      }
    }, 1000);

    // 添加元素点击事件
    document.addEventListener("click", handleElementClick);

    // 添加ESC键取消
    document.addEventListener("keydown", handleEscapeKey);
  }

  // 处理元素点击
  function handleElementClick(e) {
    if (!isPicking) return;

    e.stopPropagation();
    e.preventDefault();

    // 验证元素是否符合要求
    if (e.target.classList.contains("interface-item-nav")) {
      // 检查是否有.ant-tree-child-tree子元素
      const hasChildTree = e.target.querySelector(".ant-tree-child-tree");
      if (hasChildTree) {
        pickedElements.push({
          current: e.targe,
          children: hasChildTree.querySelectorAll("li"),
        });
        showToast(`已拾取元素，当前共 ${pickedElements.length} 个`, "success");
        // 给选中的元素添加视觉反馈
        const originalStyle = e.target.style.border;
        e.target.style.border = "2px solid #1890ff";
        setTimeout(() => {
          e.target.style.border = originalStyle;
        }, 1000);
      } else {
        showToast("拾取的元素不正确，缺少.ant-tree-child-tree子元素", "error");
      }
    } else {
      // 尝试向上查找符合条件的父元素
      const parent = e.target.closest(".interface-item-nav");
      if (parent) {
        const hasChildTree = parent.querySelector(".ant-tree-child-tree");
        if (hasChildTree) {
          pickedElements.push({
            current: parent,
            children: hasChildTree.querySelectorAll("li"),
          });
          showToast(
            `已拾取元素，当前共 ${pickedElements.length} 个`,
            "success"
          );
          // 给选中的元素添加视觉反馈
          const originalStyle = parent.style.border;
          parent.style.border = "2px solid #1890ff";
          setTimeout(() => {
            parent.style.border = originalStyle;
          }, 1000);
        } else {
          showToast(
            "拾取的元素不正确，缺少.ant-tree-child-tree子元素",
            "error"
          );
        }
      } else {
        showToast("请拾取class为interface-item-nav的元素", "error");
      }
    }
  }

  // 处理ESC键
  function handleEscapeKey(e) {
    if (e.key === "Escape" && isPicking) {
      endElementPicking(true);
    }
  }

  // 结束元素拾取
  function endElementPicking(showModal) {
    isPicking = false;

    // 移除覆盖层
    const overlay = document.getElementById("picking-overlay");
    if (overlay) {
      document.body.removeChild(overlay);
    }

    // 移除事件监听器
    document.removeEventListener("click", handleElementClick);
    document.removeEventListener("keydown", handleEscapeKey);

    // 显示弹窗
    if (showModal) {
      const modal = document.getElementById("batch-extract-modal");
      if (modal) {
        modal.style.display = "flex";
        updatePickedItemsList();
      }
    }
  }

  // 开始批量生成接口
  function startBatchGeneration() {
    // 隐藏弹窗
    const modal = document.getElementById("batch-extract-modal");
    modal.style.display = "none";

    // 收集所有URL
    batchExtractUrls = [];

    pickedElements.forEach((element) => {
      const childTree = element.children;
      if (childTree) {
        childTree.forEach((li) => {
          const aTag = li.querySelector("a.interface-item");
          if (aTag && aTag.href) {
            batchExtractUrls.push(aTag.href);
          }
        });
      }
    });
    console.log(
      "🚀 ~ startBatchGeneration ~ batchExtractUrls:",
      pickedElements,
      batchExtractUrls
    );

    if (batchExtractUrls.length === 0) {
      showToast("未找到可提取的接口URL", "error");
      return;
    }

    // 显示生成中的覆盖层
    const generatingOverlay = createGeneratingOverlay();
    document.body.appendChild(generatingOverlay);
    generatingOverlay.style.display = "flex";

    // 开始处理URL
    currentProcessingIndex = 0;
    processNextUrl();
  }

  // 创建生成中的覆盖层
  function createGeneratingOverlay() {
    const overlay = document.createElement("div");
    overlay.id = "generating-overlay";
    overlay.className = "generating-overlay";
    overlay.innerHTML = `
            <div class="generating-content">
                <div class="generating-spinner"></div>
                <p class="generating-text" id="generating-status-text">正在批量提取接口，请稍候...</p>
            </div>
        `;
    return overlay;
  }

  // 处理下一个URL
  function processNextUrl() {
    if (currentProcessingIndex >= batchExtractUrls.length) {
      // 处理完成
      const overlay = document.getElementById("generating-overlay");
      if (overlay) {
        document.body.removeChild(overlay);
      }
      pickedElements = [];
      showToast(
        `批量提取完成，共提取 ${batchExtractUrls.length} 个接口`,
        "success"
      );
      renderInterfaces();
      return;
    }

    // 更新状态文本
    const statusText = document.getElementById("generating-status-text");
    if (statusText) {
      statusText.textContent = `正在提取接口 ${currentProcessingIndex + 1}/${
        batchExtractUrls.length
      }...`;
    }

    // 保存当前窗口的URL
    const currentUrl = window.location.href;

    // 创建一个隐藏的iframe用于加载页面和提取接口
    const iframe = document.createElement("iframe");
    iframe.style.display = "none";
    iframe.src = batchExtractUrls[currentProcessingIndex];
    document.body.appendChild(iframe);

    // 添加加载完成事件

    iframe.addEventListener("load", function () {
      setTimeout(() => {
        try {
          // 使用iframe的文档执行提取接口操作
          const iframeDoc =
            iframe.contentDocument || iframe.contentWindow.document;

          // 在iframe环境中执行提取接口
          const extracted = extractInterfaceFromIframe(iframeDoc);

          if (extracted) {
            console.log(`成功提取接口 ${currentProcessingIndex + 1}`);
          }
        } catch (error) {
          console.error(`提取接口 ${currentProcessingIndex + 1} 失败:`, error);
        }

        // 移除iframe
        document.body.removeChild(iframe);

        // 处理下一个URL
        currentProcessingIndex++;
        processNextUrl();
        // setTimeout(processNextUrl, 1000); // 添加延迟避免请求过快
      }, 3000);
    });
  }

  // 从iframe中提取接口
  function extractInterfaceFromIframe(doc) {
    try {
      // 查找接口地址
      const selectors = [
        ".colValue .href",
        ".colValue",
        "td:nth-child(2)",
        ".interface-url",
        "[data-url]",
        ".url-display",
      ];

      let url = null;
      console.log("🚀 ~ extractInterfaceFromIframe ~ url:", url);
      for (const selector of selectors) {
        const element = doc.querySelector(selector);
        if (element && element.textContent.trim()) {
          url = element.textContent.trim();
          break;
        }
      }

      if (!url) {
        const text = doc.body.textContent;
        const urlMatch = text.match(/['"`]([^'"`\s]*\/mock\/[^'"`\s]*)['"`]/);
        if (urlMatch) {
          url = urlMatch[1];
        }
      }

      if (!url) {
        return false;
      }

      // 保存原始URL用于替换参数
      const originalUrl = url;
      // 保存原始URL（处理前的URL）
      const originalUrlBeforeProcessing = originalUrl;

      // 获取路径参数信息
      const pathParamMatches = url.match(/\{([^}]+)\}/g) || [];
      const hasSinglePathParam = pathParamMatches.length === 1;
      const hasMultiplePathParams = pathParamMatches.length > 1;

      // 替换路径参数 {id} -> ${id} 或 ${pathParams.id}
      url = replacePathParams(url, hasMultiplePathParams);

      // 补全相对路径
      if (!url.startsWith("http")) {
        url =
          "http://192.168.99.206:3000" + (url.startsWith("/") ? "" : "/") + url;
      }

      // 添加mock前缀配置的应用，与单个提取保持一致
      const useMockPrefix = loadMockPrefix();
      url = processMockPrefix(url, useMockPrefix);

      // 查找HTTP方法
      const methodSelectors = [".tag-method", ".http-method", ".method-tag"];
      let method = "GET";
      for (const selector of methodSelectors) {
        const element = doc.querySelector(selector);
        if (element && element.textContent.trim()) {
          method = element.textContent.trim().toUpperCase();
          break;
        }
      }

      // 查找接口名称作为注释
      let comment = "接口调用";
      const commentSelectors = [
        '//*[text()="接口名称"]/following-sibling::*',
        ".interface-name",
        ".api-name",
        ".name-label",
        "td:nth-child(1)",
      ];

      // 尝试查找"接口名称"后面的元素
      const xpathResult = doc.evaluate(
        '//*[contains(text(), "接口名称")]/following-sibling::*[1]',
        doc,
        null,
        XPathResult.FIRST_ORDERED_NODE_TYPE,
        null
      );

      if (xpathResult.singleNodeValue) {
        comment = xpathResult.singleNodeValue.textContent.trim();
      } else {
        // 回退方案
        for (const selector of commentSelectors.slice(1)) {
          const element = doc.querySelector(selector);
          if (element && element.textContent.trim()) {
            comment = element.textContent.trim();
            break;
          }
        }
      }

      // 生成函数名
      const funcName = generateFunctionName(method, url);

      // 生成参数列表
      const params = generateParams(url, method);

      // 检查是否使用axios风格
      const useAxiosStyle = loadAxiosStyle();

      // 检查是否有路径参数
      const hasPathParams = url.includes("$");

      // 生成显示代码
      let displayCode, finalCode;

      if (useAxiosStyle) {
        // axios风格
        let config = `{ url: `;
        if (hasPathParams) {
          // 有路径参数时使用模板字符串
          config += `\`${url}\``;
        } else {
          config += `'${url}'`;
        }

        if (method !== "GET") {
          config += `, method: '${method}'`;
        }

        if (method === "GET") {
          // 模拟hasTextInPage函数
          const hasRequestParams = doc.body.textContent
            .toLowerCase()
            .includes("请求参数");
          const hasQuery = doc.body.textContent.toLowerCase().includes("query");
          if (hasRequestParams && hasQuery) {
            config += `, params`;
          }
        } else if (method === "POST" || method === "PUT") {
          config += `, data`;
        }
        config += " }";

        displayCode = `axios.${method.toLowerCase()}(${config})`;
        finalCode = `/**\n * ${comment}\n */\nexport const ${funcName} = (${params}) => ${displayCode}`;
      } else {
        // 简洁风格
        let displayCodeSimple = `${method}(`;
        if (hasPathParams) {
          // 有路径参数时使用模板字符串
          displayCodeSimple += `\`${url}\``;
        } else {
          displayCodeSimple += `'${url}'`;
        }

        if (method === "GET") {
          // 模拟hasTextInPage函数
          const hasRequestParams = doc.body.textContent
            .toLowerCase()
            .includes("请求参数");
          const hasQuery = doc.body.textContent.toLowerCase().includes("query");
          if (hasRequestParams && hasQuery) {
            displayCodeSimple += ", params";
          }
        } else if (method === "POST" || method === "PUT") {
          displayCodeSimple += ", data";
        }
        displayCodeSimple += ")";

        displayCode = displayCodeSimple;
        finalCode = `/**\n * ${comment}\n */\nexport const ${funcName} = (${params}) => ${displayCode}`;
      }

      // 添加到列表，传递更多原始信息
      addInterface(
        displayCode,
        finalCode,
        comment,
        funcName,
        originalUrlBeforeProcessing,
        method
      );
      return true;
    } catch (error) {
      console.error("从iframe提取接口失败:", error);
      return false;
    }
  }
})();
